package com.prolestar.publicsentiment.domain;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.enums.CellExtraTypeEnum;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.CellExtra;
import com.alibaba.excel.metadata.data.HyperlinkData;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.util.ConverterUtils;

import com.prolestar.Enum.PublicsentimentAttentionStatus;
import com.prolestar.Enum.PublicsentimentDeleteStatus;
import com.prolestar.common.exception.ServiceException;
import com.prolestar.common.utils.DateUtils;
import com.prolestar.common.utils.DictUtils;
import com.prolestar.common.utils.SecurityUtils;
import com.prolestar.common.utils.StringUtils;
import com.prolestar.publicsentiment.mapper.PsPublicsentimentMapper;
import lombok.extern.slf4j.Slf4j;


@Slf4j
public class CommonEasyExcelListener extends AnalysisEventListener<PsPublicsentimentExc> {

    private PsPublicsentimentMapper psPublicsentimentMapper;

    int successNum = 1;
    int failureNum = 1;
    private StringBuilder successMsg = new StringBuilder();

    private StringBuilder failureMsg;

    public StringBuilder getSuccessMsg() {
        return successMsg;
    }

    public void setSuccessMsg(StringBuilder successMsg) {
        this.successMsg = successMsg;
    }

    public StringBuilder getFailureMsg() {
        return failureMsg;
    }

    public void setFailureMsg(StringBuilder failureMsg) {
        this.failureMsg = failureMsg;
    }


    public CommonEasyExcelListener(PsPublicsentimentMapper psPublicsentimentMapper){
        this.psPublicsentimentMapper = psPublicsentimentMapper;
    }





    @Override
    public void extra(CellExtra extra, AnalysisContext context) {
        // TODO Auto-generated method stub
        CellExtraTypeEnum e = extra.getType();
        super.extra(extra, context);
    }

    private Map<String, PsPublicsentimentExc> map = new HashMap<String, PsPublicsentimentExc>();


    private int totalLine = 0;
    private List<Map<Integer, String>> dataMap = new ArrayList<Map<Integer,String>>();
    private int headCount = 0;

    @Override
    public void invoke(PsPublicsentimentExc data, AnalysisContext context) {

        if(StringUtils.isNull(data)){
            throw new ServiceException("不能导入空数据！");
        }
        try {
            PsPublicsentiment publicsentiment = copy(data);
            psPublicsentimentMapper.insertPsPublicsentiment(publicsentiment);

        } catch (ParseException e) {
            throw new ServiceException("<br/>" + failureNum + "、数据类容错误 ");
        }

    }

    private PsPublicsentiment copy(PsPublicsentimentExc psPublicsentimentExc) throws ParseException {
        PsPublicsentiment publicsentiment = new PsPublicsentiment();
        String tendentiousness = null;
        String media = null;
        String releaseArea = null;
        String sourceRange = null;
            if (StringUtils.isNotEmpty(psPublicsentimentExc.getTendentiousness())){
                tendentiousness = DictUtils.getDictValue("ps_tendentiousness", psPublicsentimentExc.getTendentiousness());
            }
            if (StringUtils.isNotEmpty(psPublicsentimentExc.getMediaType())){
                media = DictUtils.getDictValue("ps_media", psPublicsentimentExc.getMediaType());
            }
            if (StringUtils.isNotEmpty(psPublicsentimentExc.getReleaseArea())){
                releaseArea = DictUtils.getDictValue("ps_possession", psPublicsentimentExc.getReleaseArea());
            }
            if (StringUtils.isNotEmpty(psPublicsentimentExc.getSourceRange())){
                sourceRange = DictUtils.getDictValue("ps_message", psPublicsentimentExc.getSourceRange());
            }
            publicsentiment.setPstitle(psPublicsentimentExc.getPsTitle());
            try {
                CellDataTypeEnum strCellType = psPublicsentimentExc.getLinkUrl().getType();
                String d = psPublicsentimentExc.getLinkUrl().getFormulaData().getFormulaValue();
                int i = d.indexOf("h");
                int i1 = d.indexOf(")") - 1;
                String substring = d.substring(i, i1);
                publicsentiment.setLinkUrl(substring);
                publicsentiment.setSrcWebset(psPublicsentimentExc.getSrcWebset());
            }catch (Exception e){
                throw new ServiceException("表格第"+failureNum +"行网址格式不正确");
            }

            if (psPublicsentimentExc.getReleaseTime() != null){
                try {
                    publicsentiment.setReleaseTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(psPublicsentimentExc.getReleaseTime()));
                } catch (Exception e) {
                    throw new ServiceException("表格第"+failureNum +"行时间格式不正确");
                }
            }else {
                publicsentiment.setReleaseTime(DateUtils.getNowDate());
            }


            publicsentiment.setKeywords(psPublicsentimentExc.getKeywords());
            publicsentiment.setPscontent(psPublicsentimentExc.getPscontent());
            publicsentiment.setNewsAuthor(psPublicsentimentExc.getNewsAuthor());
            if (psPublicsentimentExc.getReadingCount() != null){
                try {
                    publicsentiment.setReadingCount(Long.parseLong(psPublicsentimentExc.getReadingCount()));
                } catch (Exception e) {
                    throw new ServiceException("表格第"+failureNum +"行格式不正确");
                }

            }
            if (psPublicsentimentExc.getReplyCount() != null){
                try {
                    publicsentiment.setReplyCount(Long.parseLong(psPublicsentimentExc.getReplyCount()));
                } catch (Exception e) {
                    throw new ServiceException("表格第"+failureNum +"行格式不正确");
                }
            }
            if (psPublicsentimentExc.getSharesCount() != null){
                try {
                    publicsentiment.setSharesCount(Long.parseLong(psPublicsentimentExc.getSharesCount()));
                } catch (Exception e) {
                    throw new ServiceException("表格第"+failureNum +"行格式不正确");
                }
            }
            if (psPublicsentimentExc.getLikesCount() != null){
                try {
                    publicsentiment.setLikesCount(Long.parseLong(psPublicsentimentExc.getLikesCount()));
                } catch (Exception e) {
                    throw new ServiceException("表格第"+failureNum +"行格式不正确");
                }
            }
            if (psPublicsentimentExc.getWbFans() != null){
                try {
                    publicsentiment.setWbFans(Long.parseLong(psPublicsentimentExc.getWbFans()));
                } catch (Exception e) {
                    throw new ServiceException("表格第"+failureNum +"行格式不正确");
                }
            }
            if (StringUtils.isNotEmpty(tendentiousness)) {
                try {
                    publicsentiment.setTendentiousness(Long.parseLong(tendentiousness));
                } catch (Exception e) {
                    throw new ServiceException("表格第"+failureNum +"行格式不正确");
                }
            }
            if (StringUtils.isNotEmpty(media)){
                try {
                    publicsentiment.setMediaType(Long.parseLong(media));
                } catch (Exception e) {
                    throw new ServiceException("表格第"+failureNum +"行格式不正确");
                }
            }

            if (StringUtils.isNotEmpty(releaseArea)) {
                try {
                    publicsentiment.setReleaseArea(Long.parseLong(releaseArea));
                } catch (Exception e) {
                    throw new ServiceException("表格第"+failureNum +"行格式不正确");
                }
            }
            if (StringUtils.isNotEmpty(sourceRange)) {
                try {
                    publicsentiment.setSourceRange(Long.parseLong(sourceRange));
                } catch (Exception e) {
                    throw new ServiceException("表格第"+failureNum +"行格式不正确");
                }
            }
            publicsentiment.setIsDelete(PublicsentimentDeleteStatus.NODELETS);
            publicsentiment.setCreateBy(SecurityUtils.getUserId().toString());
            publicsentiment.setCreateTime(DateUtils.getNowDate());
            publicsentiment.setIsAttention(PublicsentimentAttentionStatus.NOSPECIALFOCUS);
            failureNum++;
            return publicsentiment;
    }





    @Override
    public void invokeHead(Map<Integer, ReadCellData<?>> headMap, AnalysisContext context) {
        Map<Integer, String> map = ConverterUtils.convertToStringMap(headMap, context);
        Integer rowNum = context.readRowHolder().getRowIndex();
        dataMap.add(map);
        totalLine = rowNum;
    }





    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        PsPublicsentimentExc excel = new PsPublicsentimentExc();
//        excel.setExcel1(headMap.get(0));
        excel.setPsTitle(headMap.get(1));
        excel.setReleaseTime(headMap.get(2));
        excel.setTendentiousness(headMap.get(3));
        excel.setSrcWebset(headMap.get(4));
        excel.setNewsAuthor(headMap.get(5));
        excel.setReleaseArea(headMap.get(6));
        excel.setMediaType(headMap.get(7));
        excel.setSourceRange(headMap.get(8));
        excel.setReadingCount(headMap.get(9));
        excel.setReplyCount(headMap.get(10));
        excel.setSharesCount(headMap.get(11));
        excel.setLikesCount(headMap.get(12));
        excel.setWbFans(headMap.get(13));
        //excel.setExcel15(headMap.get(14));
        excel.setPscontent(headMap.get(15));
        excel.setKeywords(headMap.get(16));
        map.put("LINE"+0, excel);
        dataMap.add(headMap);
    }




    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // TODO Auto-generated method stub

    }

    public PsPublicsentimentExc readLine(int line) {
        return map.get("LINE"+line);
    }

    public List<PsPublicsentimentExc> getAllData(){
        log.info("获取总行数:{}",map.size());
        List<PsPublicsentimentExc> list = new ArrayList<PsPublicsentimentExc>(totalLine);
        for (int i = 0; i <= map.size(); i++) {
            if(map.containsKey("LINE"+i)) {
                list.add(map.get("LINE"+i));
            }
        }
        return list;
    }

    public List<Map<Integer, String>> getAllMaps(){
        return dataMap;
    }
}

